/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * BancoTable.java
 *
 * Created on 06/08/2010, 09:28:09
 */

package com.power.powercash;

import com.db4o.ObjectContainer;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.RowSorter;
import javax.swing.table.TableColumn;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author f6036477
 */
public class ObjectTable extends javax.swing.JPanel
    implements MouseListener
{

  private ObjectTableModel model;

  private javax.swing.JScrollPane scroll;
  
  private javax.swing.JTable tabela;

  private boolean selOne;

  private int selected;

  private Editor editor;

  private JPopupMenu popup;

  private JMenuItem editar, remover;


  public ObjectTable(ObjectTableModel model) {
    this.model = model;
    initComponents();
    selOne = false;
    selected = 0;
    editor = null;

    RowSorter<ObjectTableModel> sorter =
        new TableRowSorter<ObjectTableModel>(model);
    tabela.setRowSorter(sorter);
    tabela.addMouseListener(this);
  }


  public void setEditor(Editor e)
  {
    editor = e;
  }

  
  public <T> T getSelected()
  {
    int r = tabela.getSelectedRow();
    if(r < 0 || r > model.getRowCount())
      return null;

    tabela.getValueAt(r, 0);
    return (T) model.getLast();
  }


  public void removeSelected()
  {
    int[] rows = tabela.getSelectedRows();
    if(rows != null && rows.length >= 1) {
      for(int i = rows.length-1; i >= 0; i--) {
        tabela.getValueAt(i, 0);
        model.removeObject(model.getLast());
      }//for
      model.fireTableRowsDeleted(rows[0], rows[rows.length-1]);
    }//if
  }


  public void setPreferredHeaderWidth(boolean enabled)
  {
    if(enabled)
      this.enablePreferredHeaderWidth();
    else
      this.disablePreferredHeaderWidth();
  }


  public void setPreferredHeaderWidth(int column)
  {
    this.enablePreferredHeaderWidth(column);
  }


  private void disablePreferredHeaderWidth()
  {
    tabela.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
  }


  private void enablePreferredHeaderWidth()
  {
    for(int i = 0; i < model.getColumnCount(); i++)
      this.enablePreferredHeaderWidth(i);
  }


  private void enablePreferredHeaderWidth(int column)
  {
    tabela.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    BufferedImage bi = new BufferedImage(2, 2, BufferedImage.TRANSLUCENT);
    Graphics g = bi.getGraphics();
    bi = null;
    FontMetrics fm = g.getFontMetrics(new Font("SansSerif", Font.PLAIN, 12));

    String s = model.getColumnInfo(column).getColumnName();
    int w = fm.stringWidth(s);
    TableColumn col = tabela.getColumnModel().getColumn(column);
    col.setPreferredWidth(w+15);
    g.dispose();
  }


  private void initComponents() {

    scroll = new javax.swing.JScrollPane();
    tabela = new javax.swing.JTable();

    popup = new JPopupMenu("Editar");
    editar = new JMenuItem();
    remover = new JMenuItem("Remover");

    editar.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent ae) {
        int row = tabela.getSelectedRow();
        editor.setSelected(getSelected());
        editor.openDialog((JFrame) ObjectTable.this.getTopLevelAncestor());
        tabela.setModel(model);
        //removeSelected();
        tabela.repaint();
        //setSelected(r);
      }
    });

    remover.addActionListener(new ActionListener()
    {
      @Override
      public void actionPerformed(ActionEvent ae)
      {
        removeSelected();
      }
    });

    popup.add(editar);
    popup.add(remover);

    setBorder(javax.swing.BorderFactory.createEtchedBorder());

    tabela.setModel(model);
    scroll.setViewportView(tabela);

    add(scroll);
    this.setTableSize(300, 300);
  }


  public void setTableSize(int width, int height)
  {
    Dimension dm = new Dimension(width, height);
    scroll.setSize(dm);
    scroll.setPreferredSize(dm);
  }


  @Override
  public void mouseClicked(MouseEvent e)
  {
    if(e.getButton() == MouseEvent.BUTTON3) {

      Point loc = e.getPoint();
      int r = tabela.rowAtPoint(loc);

      if(tabela.getSelectedRowCount() <= 1) {
        this.setSelected(r);
      }//if
      
      if(editor == null) popup.remove(editar);
      else {
        if(popup.getComponentIndex(editar) < 0)
          popup.add(editar);
        editar.setText("Editar "+ getSelected());
      }//else

      popup.show(tabela, loc.x, loc.y);
    }//if
  }

  public void setSelected(int row)
  {
    tabela.getSelectionModel().setSelectionInterval(row, row);
  }

  @Override
  public void mousePressed(MouseEvent e){}
  @Override
  public void mouseReleased(MouseEvent e){}
  @Override
  public void mouseEntered(MouseEvent e){}
  @Override
  public void mouseExited(MouseEvent e){}


  public static void main(String[] args)
  {
    JFrame f = new JFrame("BancoTable");
    f.setLocation(300, 150);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    File file = new File("bancos.db");
    if(file.exists())
      file.delete();

    Configuration conf = new Configuration();
    conf.setDBFile(file.getPath());
    ObjectContainer db = conf.startDB();

    
    Banco bb =  new Banco();
    Banco brad = new Banco();
    Banco itau = new Banco();
    bb.setName("BB");
    bb.setAgencia(1);
    brad.setName("Bradesco");
    brad.setAgencia(2);
    itau.setName("Itau");
    itau.setAgencia(3);

    for(int i = 1; i < 9; i++) {
      bb = bb.clone();
      bb.setConta(i*10);
      db.store(bb);

      brad = brad.clone();
      brad.setConta(i*15);
      db.store(brad);

      itau = itau.clone();
      itau.setConta(i*20);
      db.store(itau);
    }
    

    ObjectTable bt = new ObjectTable(
        new BancoTableModel(db.query(Banco.class)));
    BankEditor be = new BankEditor(db);
    bt.setEditor(be);

    f.add(bt);
    f.pack();

    f.setVisible(true);
  }

}
